package org.csu.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import org.csu.mall.common.CONSTANT;
import org.csu.mall.common.ResponseCode;
import org.csu.mall.common.UniformResponse;
import org.csu.mall.entity.Account;
import org.csu.mall.entity.Commodity;
import org.csu.mall.entity.CustomerOrder;
import org.csu.mall.entity.MerchantOrder;
import org.csu.mall.persistence.CommodityMapper;
import org.csu.mall.persistence.MerchantOrderMapper;
import org.csu.mall.service.IMerchantOrderService;
import org.csu.mall.util.DateUtil;
import org.csu.mall.util.PropertiesUtil;
import org.csu.mall.vo.CustomerOrderVO;
import org.csu.mall.vo.MerchantOrderListVO;
import org.csu.mall.vo.MerchantOrderVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service("merchantOrderService")
public class IMerchantOrderServiceImpl implements IMerchantOrderService {

    @Autowired
    private MerchantOrderMapper merchantOrderMapper;

    @Autowired
    private CommodityMapper commodityMapper;

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public UniformResponse<String> merchantOrderCancel(Long orderId, Account account) {
        if(account == null){
            return UniformResponse.createForErrorCodeMessage(
                    ResponseCode.USER_NOT_LOGIN.getCode(), ResponseCode.USER_NOT_LOGIN.getDescription());
        }

        MerchantOrder merchantOrder = merchantOrderMapper.selectById(orderId);
        if(merchantOrder.getOrderState() != CONSTANT.MerchantOrderStatus.ORDER_ON_SALE.getCode()){
            return UniformResponse.createForErrorCodeMessage(
                    ResponseCode.ORDER_CANNOT_CANCEL.getCode(), ResponseCode.ORDER_CANNOT_CANCEL.getDescription());
        }
        merchantOrder.setOrderState(CONSTANT.MerchantOrderStatus.ORDER_CANCEL_SALE.getCode());
        merchantOrder.setUpdateTime(LocalDateTime.now());
        merchantOrderMapper.updateById(merchantOrder);

        int row = commodityMapper.delete(
                Wrappers.<Commodity>query().eq("item_id", merchantOrder.getItemId()));
        if(row > 0){
            return UniformResponse.createForSuccessMessage(ResponseCode.SUCCESS.getDescription());
        }

        return UniformResponse.createForErrorMessage(ResponseCode.ERROR.getDescription());
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public UniformResponse<MerchantOrderVO> getMerchantOrderDetail(Long orderId, Account account) {
        if(account == null){
            return UniformResponse.createForErrorCodeMessage(
                    ResponseCode.USER_NOT_LOGIN.getCode(), ResponseCode.USER_NOT_LOGIN.getDescription());
        }
        if(account.getRole() == CONSTANT.Role.CUSTOMER){
            return UniformResponse.createForErrorCodeMessage(
                    ResponseCode.PERMISSION_DENIED.getCode(), ResponseCode.PERMISSION_DENIED.getDescription());
        }
        MerchantOrder merchantOrder = merchantOrderMapper.selectOne(
                Wrappers.<MerchantOrder>query().eq("order_id", orderId));
        if(merchantOrder == null){
            return UniformResponse.createForErrorCodeMessage(
                    ResponseCode.ORDER_NOT_EXIST.getCode(), ResponseCode.ORDER_NOT_EXIST.getDescription());
        }
        MerchantOrderVO merchantOrderVO = this.entityToVO(merchantOrder);
        return UniformResponse.createForSuccess(ResponseCode.SUCCESS.getDescription(), merchantOrderVO);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public UniformResponse<MerchantOrderListVO> getMerchantOrderList(Long orderId, String keyword, int pageSize,
                                                                     int pageNum, Integer orderSource, Integer orderState,
                                                                     Account account) {
        if(account == null){
            return UniformResponse.createForErrorCodeMessage(
                    ResponseCode.USER_NOT_LOGIN.getCode(), ResponseCode.USER_NOT_LOGIN.getDescription());
        }
        if(account.getRole() == CONSTANT.Role.CUSTOMER){
            return UniformResponse.createForErrorCodeMessage(
                    ResponseCode.PERMISSION_DENIED.getCode(), ResponseCode.PERMISSION_DENIED.getDescription());
        }

        Page<MerchantOrder> result = new Page<>();
        result.setCurrent(pageNum);
        result.setSize(pageSize);

        QueryWrapper<MerchantOrder> queryWrapper = new QueryWrapper<>();
        //增加用户角色查询
        if(account.getRole() == CONSTANT.Role.AUTHENTICATION){
            queryWrapper.eq("merchant_id", account.getUserId());
        }
        //增加关键字查询
        if(StringUtils.isNotBlank(keyword)){
            keyword = new StringBuilder().append("%").append(keyword).append("%").toString();
            queryWrapper.like("order_name", keyword);
        }
        //增加订单来源查询
        if(orderSource != CONSTANT.CommoditySource.ALL_SALE.getCode()){
            queryWrapper.eq("order_source", orderSource);
        }
        //增加订单状态查询
        if(orderState != -1){
            queryWrapper.eq("order_stare", orderState);
        }
        result = merchantOrderMapper.selectPage(result, queryWrapper);
        MerchantOrderListVO merchantOrderListVO = this.pageToVO(result);
        return UniformResponse.createForSuccess(
                ResponseCode.SUCCESS.getDescription(), merchantOrderListVO);
    }

    private MerchantOrderVO entityToVO(MerchantOrder merchantOrder){
        MerchantOrderVO merchantOrderVO = new MerchantOrderVO();
        merchantOrderVO.setOrderId(merchantOrder.getOrderId());
        merchantOrderVO.setOrderName(merchantOrder.getOrderName());
        merchantOrderVO.setItemId(merchantOrder.getItemId());
        merchantOrderVO.setItemName(merchantOrder.getItemName());
        merchantOrderVO.setItemNumber(merchantOrder.getItemNumber());
        merchantOrderVO.setUnitPrice(merchantOrder.getUnitPrice());
        merchantOrderVO.setTotalPrice(merchantOrder.getTotalPrice());
        merchantOrderVO.setOrderSource(merchantOrder.getOrderSource());
        merchantOrderVO.setOrderState(merchantOrder.getOrderState());
        merchantOrderVO.setMerchantID(merchantOrder.getMerchantId());
        merchantOrderVO.setMPhone(merchantOrder.getPhoneNumber());
        merchantOrderVO.setMAddress(merchantOrder.getAddress());
        //新增
        merchantOrderVO.setCreateTime(DateUtil.localDateTimeToString(merchantOrder.getCreateTime()));
        merchantOrderVO.setUpdateTime(DateUtil.localDateTimeToString(merchantOrder.getUpdateTime()));
        if(merchantOrder.getEndTime() != null){
            merchantOrderVO.setEndTime(DateUtil.localDateTimeToString(merchantOrder.getEndTime()));
        }
        Commodity commodity = commodityMapper.selectOne(
                Wrappers.<Commodity>query().eq("item_id", merchantOrder.getItemId()));
        if(commodity != null){
            merchantOrderVO.setImg(commodity.getImage());
        }else{
            merchantOrderVO.setImg("item.jpg");
        }
        merchantOrderVO.setImgHost(PropertiesUtil.getProperty("image.server.url"));
        return merchantOrderVO;
    }

    private MerchantOrderListVO pageToVO(Page<MerchantOrder> result){
        MerchantOrderListVO merchantOrderListVO = new MerchantOrderListVO();
        merchantOrderListVO.setPageNum(result.getCurrent());
        merchantOrderListVO.setPageSize(result.getSize());
        merchantOrderListVO.setStartRow(1);
        merchantOrderListVO.setEndRow(result.getPages());
        merchantOrderListVO.setTotal(result.getTotal());
        merchantOrderListVO.setPages(result.getPages());
        List<MerchantOrder> merchantOrderList = result.getRecords();
        List<MerchantOrderVO> merchantOrderVOList = Lists.newArrayList();
        for(MerchantOrder merchantOrder: merchantOrderList){
            merchantOrderVOList.add(this.entityToVO(merchantOrder));
        }
        merchantOrderListVO.setMerchantOrderVOList(merchantOrderVOList);
        merchantOrderListVO.setFirstPage(1l);
        merchantOrderListVO.setPrePage(result.getCurrent() - 1);
        merchantOrderListVO.setNextPage(result.getCurrent() +1);
        merchantOrderListVO.setIsFirstPage(result.getCurrent() == 1);
        merchantOrderListVO.setIsLastPage(result.getCurrent() == result.getPages());
        merchantOrderListVO.setHasPreviousPage(result.getCurrent() > 1);
        merchantOrderListVO.setHasNextPage(result.getCurrent() < result.getPages());
        merchantOrderListVO.setImgHost(PropertiesUtil.getProperty("image.server.url"));
        return merchantOrderListVO;
    }
}
